#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
K713专业版PLOOP处理脚本
参考K717效果，生成专业工程图纸风格的SVG
"""

import os
import sys
import json
from datetime import datetime

# 添加模块路径
sys.path.append('.')

from enhanced_ploop_processor import EnhancedPLoopProcessor
from generate_professional_svg import generate_professional_svg

def main():
    print("=== K713专业版PLOOP处理器 ===")
    
    # 输入输出路径
    input_file = "test-data/1KA-ARCH-P-R-K713.txt"
    output_dir = "results_k713_professional"
    
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)
    
    # 检查输入文件
    if not os.path.exists(input_file):
        print(f"错误：输入文件不存在 - {input_file}")
        return
    
    print(f"输入文件: {input_file}")
    print(f"输出目录: {output_dir}")
    
    # 初始化处理器
    processor = EnhancedPLoopProcessor()
    
    try:
        # 解析文件
        print("\n--- 解析PLOOP数据 ---")
        ploop_data = processor.parse_file(input_file)
        
        if not ploop_data:
            print("错误：解析失败，未找到有效的PLOOP数据")
            return
        
        print(f"解析成功，发现 {len(ploop_data)} 个PLOOP")
        
        # 处理第一个PLOOP（通常K713只有一个）
        ploop = ploop_data[0]
        framework_name = ploop.get('framework_name', 'Unknown')
        print(f"处理框架: {framework_name}")
        
        # 增强处理
        print("\n--- 增强处理 ---")
        processed_data = processor.process_ploop_enhanced(ploop)
        
        # 输出处理统计
        original_count = processed_data['original_vertices_count']
        optimized_count = processed_data['optimized_vertices_count']
        optimization_rate = processed_data['optimization_rate']
        total_perimeter = processed_data['total_perimeter']
        fradius_count = processed_data['fradius_vertices_count']
        
        print(f"原始顶点: {original_count}")
        print(f"优化后顶点: {optimized_count}")
        print(f"优化率: {optimization_rate:.1f}%")
        print(f"总周长: {total_perimeter:.2f}mm")
        print(f"FRADIUS顶点: {fradius_count}")
        
        # 生成专业SVG
        print("\n--- 生成专业SVG ---")
        svg_file = os.path.join(output_dir, "k713_professional.svg")
        svg_content = generate_professional_svg(
            processed_data, 
            framework_name,
            width=1000,
            height=800
        )
        
        with open(svg_file, 'w', encoding='utf-8') as f:
            f.write(svg_content)
        
        print(f"专业SVG已生成: {svg_file}")
        
        # 生成处理报告
        print("\n--- 生成处理报告 ---")
        report = {
            'framework_name': framework_name,
            'processing_time': datetime.now().isoformat(),
            'input_file': input_file,
            'original_vertices_count': original_count,
            'optimized_vertices_count': optimized_count,
            'optimization_rate': optimization_rate,
            'total_perimeter': total_perimeter,
            'fradius_vertices_count': fradius_count,
            'height': processed_data['height'],
            'processed_vertices': processed_data['processed_vertices'],
            'fradius_info': processed_data['fradius_info'],
            'files_generated': {
                'svg': 'k713_professional.svg',
                'report': 'k713_professional_report.json',
                'analysis': 'k713_professional_analysis.md'
            }
        }
        
        # 保存JSON报告
        report_file = os.path.join(output_dir, "k713_professional_report.json")
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        
        print(f"处理报告已生成: {report_file}")
        
        # 生成分析文档
        analysis_file = os.path.join(output_dir, "k713_professional_analysis.md")
        analysis_content = f"""# K713专业版PLOOP分析报告

## 基本信息
- **框架名称**: {framework_name}
- **处理时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- **输入文件**: {input_file}

## 处理统计
- **原始顶点数**: {original_count}
- **优化后顶点数**: {optimized_count}
- **优化率**: {optimization_rate:.1f}%
- **总周长**: {total_perimeter:.2f}mm
- **PLOOP高度**: {processed_data['height']}mm
- **FRADIUS顶点数**: {fradius_count}

## 顶点坐标详情
"""

        # 添加顶点表格
        analysis_content += "| 序号 | X坐标 (mm) | Y坐标 (mm) | FRADIUS (mm) |\n"
        analysis_content += "|------|------------|------------|---------------|\n"
        
        for i, vertex in enumerate(processed_data['processed_vertices']):
            x = vertex['x']
            y = vertex['y']
            fradius = vertex.get('fradius', 0.0)
            fradius_str = f"{fradius:.2f}" if fradius > 0 else "-"
            analysis_content += f"| {i} | {x:.2f} | {y:.2f} | {fradius_str} |\n"

        if processed_data['fradius_info']:
            analysis_content += f"\n## FRADIUS圆弧信息\n"
            for i, info in enumerate(processed_data['fradius_info']):
                analysis_content += f"- **圆弧 {i+1}**: 半径 {info['radius']:.2f}mm，顶点 {info['vertex_index']}\n"

        analysis_content += f"""
## 文件信息
- **专业SVG**: k713_professional.svg
- **处理报告**: k713_professional_report.json
- **分析文档**: k713_professional_analysis.md

## 技术特性
- 完整XY坐标系统和精确刻度标记
- 双层级网格线（0.1和0.2透明度）
- 详细顶点坐标表（序号、X、Y、FRADIUS）
- FRADIUS圆弧橙色标记和数值
- 工程图纸风格布局和专业配色

---
*生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""

        with open(analysis_file, 'w', encoding='utf-8') as f:
            f.write(analysis_content)
        
        print(f"分析文档已生成: {analysis_file}")
        
        print(f"\n=== K713专业版处理完成 ===")
        print(f"所有文件已保存到: {output_dir}/")
        
        # 输出简要信息用于对比
        print(f"\n=== 简要统计 ===")
        print(f"顶点优化: {original_count} → {optimized_count} (优化率 {optimization_rate:.1f}%)")
        print(f"总周长: {total_perimeter:.2f}mm")
        print(f"FRADIUS: {fradius_count} 个")
        
        # 输出顶点坐标供对比
        print(f"\n=== 顶点坐标 ===")
        for i, vertex in enumerate(processed_data['processed_vertices']):
            x = vertex['x']
            y = vertex['y']
            fradius = vertex.get('fradius', 0.0)
            if fradius > 0:
                print(f"顶点 {i}: ({x:.2f}, {y:.2f}) FRADIUS={fradius:.2f}")
            else:
                print(f"顶点 {i}: ({x:.2f}, {y:.2f})")
        
    except Exception as e:
        print(f"处理过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main() 